#!/usr/bin/env python
#################################################################################
#   Copyright (C) 2007 Tim Kersten                                              #
#   (See the file AUTHORS for details.)                                         #
#                                                                               #
#   PyMeteor is free software; you can redistribute it and/or modify            #
#   it under the terms of the GNU General Public License as published by        #
#   the Free Software Foundation; either version 2 of the License, or           #
#   (at your option) any later version.                                         #
#                                                                               #
#   PyMeteor is distributed in the hope that it will be useful,                 #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of              #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                #
#   GNU General Public License for more details.                                #
#                                                                               #
#   You should have received a copy of the GNU General Public License           #
#   along with PyMeteor; if not, write to the Free Software                     #
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA    #
#   or visit http://www.gnu.org/licenses/gpl.txt                                #
#                                                                               #
#################################################################################


VERSION = "0.1.0alpha3"

import sys, os, urllib, urllib2, httplib, cookielib
try:
	import pygtk
	pygtk.require("2.0")
except:
	print "Could not import pygtk"

try:
	import gtk
	import gtk.glade
except:
	print "Could not import gtk"
	sys.exit(1)

import tray, mymeteor

## Find out the location of pymeteor's working directory, and go there
basedir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(basedir, "pymeteor.py")):
    if os.path.exists(os.path.join(os.getcwd(), "pymeteor.py")):
        basedir = os.getcwd()
sys.path.insert(0, basedir)
os.chdir(basedir)

class PyMeteor:
	"""
	The main interface class
	"""
	
	def __init__(self):
		"""
		Initialise the main window
		"""
		
		self.version = VERSION
		
		self.title = "PyMeteor"
		self.phoneNumber = "";
		self.pin = "";
		self.to = "";
		self.message = "";
				
		self.gladefile = "pymeteor.glade"
		self.xml = gtk.glade.XML(self.gladefile)
		
		self.loginDialog = self.xml.get_widget("login_dialog")
		self.window = self.xml.get_widget("main_window")
		self.messagesLeft = self.xml.get_widget("smsLeft_label")
		self.window.set_size_request(300, 170)

		self.active = False
		
		self.mymeteor = mymeteor.MyMeteor()
		
		menu = tray.Menu()
		menu.append("Login", self.showLoginDialog)
		menu.append_separator()
		menu.append("Quit", self.quit)
		self.tray_icon = tray.TrayIcon(self, "trayicon.png", menu)
		self.tray_icon.set_tooltip("PyMeteor " + self.version)
		self.tray_icon.activate = self.toggleWindow
		
		self.connectEvents()

	def connectEvents(self):
		"""
		Connect events to the various widgets
		"""
		
		self.window.connect("delete_event", self.on_Close)
		self.loginDialog.connect("delete_event", self.hideLoginDialog)
		self.xml.get_widget("login_button").connect("clicked", self.login)
		self.xml.get_widget("cancel_button").connect("clicked", self.hideLoginDialog)
		self.xml.get_widget("phoneNumber_entry").connect("changed", self.updateLoginDetails)
		self.xml.get_widget("pin_entry").connect("changed", self.updateLoginDetails)
		self.xml.get_widget("to_entry").connect("changed", self.updateMessageDetails)
		self.xml.get_widget("message_textview").connect("key-release-event", self.updateMessageDetails)
		self.xml.get_widget("send_button").connect("clicked", self.sendMessage)

	def toggleWindow(self, widget=None, event=None):
		self.active = not self.active
		if(self.active):
			self.window.show()
		else:
			self.window.hide()

	def showLoginDialog(self, widget=None, event=None):
		self.loginDialog.show()

	def hideLoginDialog(self, widget=None, event=None):
		self.loginDialog.hide()
		return True

	def login(self, widget=None, event=None):
		if self.mymeteor.login(self.phoneNumber, self.pin):
			self.hideLoginDialog()
			self.updateMessagesLeft()

	def updateMessagesLeft(self):
		self.messagesLeft.set_text("("+self.mymeteor.getMessagesLeft()+" SMS left)")

	def updateLoginDetails(self, widget=None, event=None):
		if widget.get_name() == "phoneNumber_entry":
			self.phoneNumber = widget.get_text()
		elif widget.get_name() == "pin_entry":
			self.pin = widget.get_text()

	def updateMessageDetails(self, widget=None, event=None):
		if widget.get_name() == "to_entry":
			self.to = widget.get_text()
		elif widget.get_name() == "message_textview":
			start, end = widget.get_buffer().get_bounds()
			self.message = widget.get_buffer().get_text(start, end)
		if 306 - len(self.message) < 0:
			self.message = self.message[:306]
			widget.get_buffer().set_text(self.message)
		charsLeft = 306 - len(self.message)
		self.xml.get_widget("charsLeft_label").set_label( str(charsLeft) + " chars left" )
	
	def sendMessage(self, widget=None, event=None):
		if self.to < 10:
			return False
		if self.mymeteor.sendMessage(self.to, self.message):
			self.window.hide()
			self.active = False
			self.updateMessagesLeft()

	def on_Close(self, widget=None, event=None):
		self.window.hide()
		self.active = False
		#self.palette.close()
		return True
		#gtk.main_quit()

	def quit(self, widget=None, event=None):
		gtk.main_quit()

if __name__ == "__main__":
	pymeteor = PyMeteor()
	gtk.main()
